package com.huan.controller;

import com.huan.VO.AdminUserInfoVo;
import com.huan.VO.AdminUserRouterVo;
import com.huan.VO.UserInfoVo;
import com.huan.domain.AppHttpCodeEnum;
import com.huan.domain.ResponseResult;
import com.huan.domain.entity.User;
import com.huan.domain.entity.loginuser;
import com.huan.security.exception.SystemException;
import com.huan.service.LoginService;
import com.huan.service.MenuService;
import com.huan.service.RoleService;
import com.huan.utils.BeanCopyUtil;
import com.huan.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user) throws Exception {
        if(!StringUtils.hasText(user.getUserName())){
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }
    @GetMapping("getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){
//        查询用户信息，权限信息，角色信息，并且封装成对应的VO进行返回
        loginuser user = SecurityUtils.getLoginUser();
        User userUser = user.getUser();
        UserInfoVo userInfoVo = BeanCopyUtil.resultVO(userUser, UserInfoVo.class);
        List<String> perms = menuService.selectPermsByUserId(user.getUser().getId());
        //根据用户id查询角色信息
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(user.getUser().getId());

        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roleKeyList,userInfoVo);
        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult<AdminUserInfoVo> getRouters(){
//        查询menu，并以tree的方式返回
        Long id = SecurityUtils.getUserId();
        AdminUserRouterVo adminUserRouterVo = menuService.selectRouterMenuTreeByUserId(id);
        return ResponseResult.okResult(adminUserRouterVo);
    }
    @PostMapping("/user/logout")
    public ResponseResult logout() throws Exception {

        return loginService.logout();
    }























}